package cn.zhku.news.dao;

import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.zhku.news.domain.News;
import cn.zhku.user.service.UserException;


public class NewsDao {
	private QueryRunner qr = new TxQueryRunner();
	
	public ArrayList<News> findAll() {
		try {
			String sql = "select * from news";
		return (ArrayList<News>) qr.query(sql,new BeanListHandler<News>(News.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void add(News news) {
		try {
			String sql = "insert into news values(?,?,?,?,?,?,?)";
			Object[] params = {news.getNid(),news.getAid(),
			news.getTitle(),news.getContent(),news.getImage(),
			news.getDate(),news.getCategory()};
			
			qr.update(sql, params);
		} catch(SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void edit(News news) {
		try {
			String sql = "UPDATE news SET  title=?, content=?, image=?, date=?, category=?"
					+ "WHERE nid = ?";
			Object[] params = {news.getTitle(),news.getContent(),news.getImage(),
					news.getDate(),news.getCategory(),news.getNid()};
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
	}

	public void delete(News news) {
		try {
			String sql = "delete from news where nid = ?";
			qr.update(sql,news.getNid());
		} catch (SQLException e) {
			throw new  RuntimeException(e);
		}
		
	}

}
